package com.example.classroom.service;

import com.example.classroom.entity.Classroom;
import com.example.classroom.entity.UpdateClassroom;
import com.example.classroom.mapper.ClassroomMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.concurrent.TimeUnit;


import java.util.List;

@Service
public class ClassroomService {

    @Autowired
    private ClassroomMapper classroomMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public List<Classroom> findAllClassroom() {
        String redisKey = "classrooms"; // 缓存的 key
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();

        // 1. 尝试从缓存中获取数据
        List<Classroom> classrooms = (List<Classroom>) ops.get(redisKey);
        if (classrooms != null) {
            return classrooms; // 缓存命中，直接返回
        }

        // 2. 缓存未命中，查询数据库
        classrooms = classroomMapper.findAll();

        // 3. 将查询结果写入 Redis 缓存，设置过期时间
        ops.set(redisKey, classrooms, 10, TimeUnit.MINUTES);

        return classrooms;
    }


    public int addClassroom(Classroom classroom) {
        classroomMapper.insertClassroom(classroom);

        // 清理缓存
        redisTemplate.delete("classrooms");

        return classroom.getId();
    }

    public int removeClassroom(int id) {
        int result = classroomMapper.deleteClassroom(id);

        // 清理缓存
        redisTemplate.delete("classrooms");

        return result;
    }

    public int updateClassroom(int id, UpdateClassroom updateClassroom) {
        int result = classroomMapper.updateClassroom(id, updateClassroom);

        // 清理缓存
        redisTemplate.delete("classrooms");

        return result;
    }


    public List<Classroom> searchClassroom(String name, String building, int capacity) {
        String redisKey = "classrooms_search_" + name + "_" + building + "_" + capacity;
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();

        // 尝试从缓存中获取数据
        List<Classroom> classrooms = (List<Classroom>) ops.get(redisKey);
        if (classrooms != null) {
            return classrooms; // 缓存命中
        }

        // 查询数据库
        classrooms = classroomMapper.searchClassroom(name, building, capacity);

        // 缓存数据
        ops.set(redisKey, classrooms, 10, TimeUnit.MINUTES);

        return classrooms;
    }

}
